// 这是一个关于同步与互斥的测试代码
#include <iostream>
#include <pthread.h>
#include<vector>
#include <mutex>
#include <string>
#include<unistd.h>
// 添加条件变量，可以解决单一添加互斥锁导致的线程饥饿问题
using namespace std;
pthread_cond_t _cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t _mutex=PTHREAD_MUTEX_INITIALIZER;
int num = 1000;

void *threadrun(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
    //上锁
    pthread_mutex_lock(&_mutex);
    //让线程等待
    pthread_cond_wait(&_cond,&_mutex);//第二个参数的作用，因为在线程等待的时候不能一直占着锁，需要把锁让出来
    std::cout<<"线程-"<<name.c_str()<<num++<<std::endl;
    //解锁
    pthread_mutex_unlock(&_mutex);
    }
    return nullptr;
}
int main()
{
    std::vector<pthread_t> threads;
    for (int i = 0; i < 5; i++)
    {
        pthread_t tid;
        char *name = new char[64];
        snprintf(name, 64, "thread-%d", i);
        int n = pthread_create(&tid, nullptr, threadrun, name);
        if (n != 0)
            continue;
        threads.push_back(tid);
        sleep(1);
    }
    //每隔1秒唤醒一个线程
    while(true)
    {
        //唤醒
        pthread_cond_signal(&_cond);
        std::cout<<"唤醒一个线程"<<std::endl;
        sleep(1);
    }
    for(int i = 0;i<5;i++)
    {
        pthread_join(threads[i],nullptr);
    }
    pthread_mutex_destroy(&_mutex);
    pthread_cond_destroy(&_cond);
    return 0;
}